const Koa = require('koa');
const formidable = require('formidable');
const app = new Koa();
const path = require('path')
const Router = require('koa2-router');
const send = require('koa-send')
const DB = require('./src/db')

const router = new Router({})

// throw an error anywhere you want!
router.get('/404', ctx => ctx.throw(404));
router.get('/500', ctx => ctx.throw(500));

router.get('/download/:userId', async (ctx) => {
  // console.log('ctx.params.userId', ctx.params.userId)
  try {
    let val = DB.getDB().get('posts').find({ title: ctx.params.userId + '' }).value()
    // console.log('val', val)
    if (val) {
      // ctx.body =  JSON.stringify(val)
      if (val.files && val.files.koaFiles && val.files.koaFiles.path) {
        let file_path = path.resolve(__dirname, val.files.koaFiles.path)
        ctx.attachment(file_path)
        try {
          await send(ctx, file_path);
        } catch(e) {
          ctx.throw(404, '文件不存在')
        }
      } else {
        ctx.throw(404, '文件不存在')
      }
    } else {
      ctx.throw(404, '文件不存在')
    }
  } catch(e) {
    console.error(e)
    ctx.body =  ''
  }
});

router.get('/ui/upload', (ctx)=> {
    // show a file upload form
    ctx.set('Content-Type', 'text/html');
    ctx.status = 200;
    ctx.body = `
      <h2>With <code>"koa"</code> npm package</h2>
      <form action="/api/upload" enctype="multipart/form-data" method="post">
      <div>Text field title: <input type="text" name="title" /></div>
      <div>File: <input type="file" name="koaFiles" multiple="multiple" /></div>
      <input type="submit" value="Upload" />
      </form>
    `;
})

router.get('/api/uploadd', (ctx) => {
  ctx.body = 'upload finish'
})

router.post('/api/upload', async (ctx, next) => {
  const form = formidable({ multiples: true, keepExtensions: true });

  // not very elegant, but that's for now if you don't want to use `koa-better-body`
  // or other middlewares.
  await new Promise((resolve, reject) => {
    form.parse(ctx.req, (err, fields, files) => {
      if (err) {
        console.error('err', err)
        reject(err);
        return;
      }

      ctx.set('Content-Type', 'application/json');
      ctx.status = 200;
      ctx.state = { title: fields.title, fields, files };
      ctx.body = JSON.stringify(ctx.state, null, 2);
      DB.addPost(ctx.state)
      resolve();
    });
  });
})

app.use(router);

app.on('error', (err) => {
  console.error('server error', err);
});

app.use((ctx) => {
  console.log('The next middleware is called');
  console.log('Results:', ctx.state);
});

app.listen(3000, () => {
  console.log('Server listening on http://localhost:3000 ...');
});